package com.rtsapp.server.network.protocol.crypto.client;

import com.rtsapp.server.logger.Logger;
import com.rtsapp.server.logger.LoggerFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;


/**
 * RSAHandshakeHandler
 */
public class ClientRSAHandshakeHandler extends ChannelInboundHandlerAdapter {

    private static final Logger LOG = LoggerFactory.getLogger(ClientRSAHandshakeHandler.class);

    private final ClientRSAHandshake handshake;

    public ClientRSAHandshakeHandler(ClientRSAHandshake handshake) {
        this.handshake = handshake;
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (msg instanceof ByteBuf) {

            ByteBuf data = (ByteBuf) msg;

            //这一步不能删除, readInt将可读索引玩后移动，跳过长度字段
            int length = data.readInt();

            try {
                handshake.recvData(data);

            } catch (Throwable ex) {
                handshake.closeUnexpectedly(ex, "channelRead error");
            } finally {
                //释放引用计数
                data.release();
            }
        } else {
            handshake.closeUnexpectedly("channelRead msg is not ByteBuf..");
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        handshake.closeUnexpectedly(cause, cause.getMessage());
    }


}
